package com.example.mydemoproject.task;

import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * @author LiuZhiYong
 * @description
 * @date 2022-09-29
 **/
public class Task extends RecursiveTask<Boolean> {

    private int start;
    private int end;
    private int maxValue = 1;

    private List list;

    public Task(int start, int end, List list) {
        this.start = start;
        this.end = end;
        this.list = list;
    }

    @Override
    protected Boolean compute() {
        if (end - start <= maxValue) {
            for (int i = start; i <= end; i++) {
                long id = Thread.currentThread().getId();
                System.out.println(id + ":" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            return true;
        }
        int middle = start + (end - start)/2;

        int start1 = start;
        int end1 = middle;

        int start2 =middle + 1;
        int end2 = end;

        Task task1 = new Task(start1, end1, list);
        Task task2 = new Task(start2, end2, list);

        task1.fork();
        task2.fork();

        Boolean join1 = task1.join();
        Boolean join2 = task2.join();

        return Boolean.TRUE.equals(join1) && Boolean.TRUE.equals(join2);
    }
}
